package com.JUC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JUC03_CustomizedCommunication {
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();
        new Thread(()->{shareResource.printA();},"Thread_A").start();
        new Thread(()->{shareResource.printB();},"Thread_BB").start();
        new Thread(()->{shareResource.printC();},"Thread_CCC").start();
    }
}
class ShareResource{
    //标志位 ：A-0 ; B-1 ; C-2
    private int state = 0;
    private Lock lock = new ReentrantLock();
    // 因为有三个线程所以需要三个 condition 对象
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();

    public void printA() {
        print(0, conditionA, conditionB);
    }
    public void printB() {
        print(1, conditionB, conditionC);
    }
    public void printC() {
        print(2, conditionC, conditionA);
    }

    /**
     * @param currentState ：该线程对应的 标志位
     * @param currentCondition ： 当前线程 对应的 condition 对象
     * @param nextCondition ： 当前线程的下一个线程 对应的 condition 对象
     */
    private void print(int currentState, Condition currentCondition, Condition nextCondition) {
        // 循环 10 轮
        for (int i = 0; i < 10; ) {
            //上锁
            lock.lock();
            try {
                while (state % 3 != currentState) {
                    currentCondition.await();
                }
                for (int j = 0; j < (state % 3 + 1); j++){
                    System.out.println(Thread.currentThread().getName() + " print " + (j+1));
                }
                state++;
                i++;
                nextCondition.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
